package com.lixin.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 生产者
 * 简单模式simple
 * rabbitmq基于amqp协议
 */
public class Producer {
    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.3.17");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("123456");
        factory.setVirtualHost("/");
        try {
            // 创建连接connection
            connection = factory.newConnection("adminConn");
            // 创建通道channel
            channel = connection.createChannel();
            // 创建消息队列
            String queueName = "order";
            channel.queueDeclare(
                    queueName, // 队列名称
                    false, // 消息是否持久化
                    false, // 是否是独占队列
                    false, // 最后一个消费者消费完消息后，是否将队列删除
                    null // 携带的附加参数
            );
            // 准备消息内容
            String message = "创建订单";
            // 发送消息给队列queue
            channel.basicPublish("", queueName, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println("消息成功发送！");
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
